﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace DiPlaner.Profile
{/*
    public partial class BotSetupForm : Form
    {
        #region vars

        public BotProfile.BotData CurentBot;
        public string workPlan = "unlim";
        public int Index;
        private string db_path = "";
        private string d3_path = "";
        public static Point syssize;
        #endregion

        #region External
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int left, top, right, bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct WINDOWINFO
        {
            public uint cbSize;
            public RECT rcWindow;
            public RECT rcClient;
            public uint dwStyle;
            public uint dwExStyle;
            public uint dwWindowStatus;
            public uint cxWindowBorders;
            public uint cyWindowBorders;
            public ushort atomWindowType;
            public ushort wCreatorVersion;

            public WINDOWINFO(Boolean? filler)
                : this()   // Allows automatic initialization of "cbSize" with "new WINDOWINFO(null/true/false)".
            {
                cbSize = (UInt32)(Marshal.SizeOf(typeof(WINDOWINFO)));
            }

        }

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi);
        #endregion

        public BotSetupForm()
        {
            InitializeComponent();
        }

        private void bt_wiz_Click(object sender, EventArgs e)
        {
            var fantoms = new List<Form>();
            DiForm.BotLines.ForEach(a => fantoms.Add(new FantomMarker()));

            var pwi = new WINDOWINFO();
            GetWindowInfo(Handle, ref pwi);
            syssize = new Point
                          {
                              X = (pwi.rcClient.left - pwi.rcWindow.left) + (pwi.rcWindow.right - pwi.rcClient.right),
                              Y = (pwi.rcWindow.bottom - pwi.rcClient.bottom) + (pwi.rcClient.top - pwi.rcWindow.top)
                          };

            using (var wm = new WinMarker())
            {
                for (var i = 0; i < fantoms.Count; i++)
                {
                    if (i == Index) continue;

                    fantoms[i].Show();
                    fantoms[i].Text = "Bot #" + (i + 1);
                    fantoms[i].Size = DiForm.BotLines[i].profile.Bot.size;
                    fantoms[i].Location = DiForm.BotLines[i].profile.Bot.pos;
                }
                wm.Size = new Size((int)ns_x.Value, (int)ns_y.Value);
                wm.MinimumSize = new Size(200, 150);
                wm.Location = new Point((int)np_x.Value, (int)np_y.Value);
                wm.sys = syssize;
                wm.ShowDialog();
                try
                {
                    np_x.Value = wm.pos.X; np_y.Value = wm.pos.Y;
                    ns_x.Value = wm.size.Width; ns_y.Value = wm.size.Height;
                }
                catch { }

                fantoms.ForEach(f => f.Hide());
            }
        }

        private void BotSetupForm_Load(object sender, EventArgs e)
        {
            LoadData();
            DiForm.BotLines.ForEach(a => cb_copyFrom.Items.Add(
                a.line_lb_name.Text.Length > 0 ?
                a.line_lb_name.Text :
                a.Index.ToString(CultureInfo.InvariantCulture)
                ));
        }
        
        private void bt_save_Click(object sender, EventArgs e)
        {
            CurentBot.db_key = tx_key.Text;
            CurentBot.bnet = tx_login.Text;
            CurentBot.pass = tx_pass.Text;
            CurentBot.db_routine = tx_routine.Text;

            CurentBot.d3_path = d3_path;
            CurentBot.db_path = db_path;

            CurentBot.pos = new Point((int)np_x.Value, (int)np_y.Value);
            CurentBot.size = new Size((int)ns_x.Value, (int)ns_y.Value);

            workPlan = tb_schedulePlan.Text;

            DialogResult = DialogResult.OK;
        }

        private void bt_cancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void path_Click(object sndr, EventArgs e)
        {
            var sender = (Button)sndr;
            var type = sender.Name.Substring(3, 2);

            switch (type)
            {
                case "d3":
                    openD3File.Filter = "Diablo III.exe|*.exe";
                    openD3File.Title = "Select Diablo III.exe";
                    openD3File.InitialDirectory = DiForm._lastd3_path;
                    openD3File.ShowDialog();
                    if (openD3File.FileName.Length > 0)
                    {
                        d3_path = openD3File.FileName;
                        Checker(sndr, e);
                    }
                    DiForm._lastd3_path = d3_path.Substring(0, d3_path.LastIndexOf('\\') - 1);
                    break;
                case "db":
                    openDBFile.Filter = "Demonbuddy.exe|*.exe";
                    openDBFile.Title = "Select Demonbuddy.exe";
                    openDBFile.InitialDirectory = DiForm._lastdb_path;
                    openDBFile.ShowDialog();
                    if (openDBFile.FileName.Length > 0)
                    {
                        db_path = openDBFile.FileName;
                        Checker(sndr, e);
                    }
                    DiForm._lastdb_path = db_path.Substring(0, db_path.LastIndexOf('\\') - 1);
                    break;
            }
        }

        private void ValueChanged(object sender, EventArgs e)
        {
            var snd = (NumericUpDown)sender;
            if (snd.Value > snd.Maximum) snd.Value = snd.Maximum;
            if (snd.Value < snd.Minimum) snd.Value = snd.Minimum;
        }

        private void lb_d3_set_MouseEnter(object sender, EventArgs e)
        {
            toolTip1.SetToolTip((Label)sender, CurentBot.d3_path);
        }

        private void bt_d3_path_MouseEnter(object sender, EventArgs e)
        {
            toolTip1.SetToolTip((Button)sender, CurentBot.d3_path);
        }

        private void lb_db_set_MouseEnter(object sender, EventArgs e)
        {
            toolTip1.SetToolTip((Label)sender, CurentBot.db_path);
        }

        private void bt_db_path_MouseEnter(object sender, EventArgs e)
        {
            toolTip1.SetToolTip((Button)sender, CurentBot.db_path);
        }

        private void btn_copyPlan_Click(object sender, EventArgs e)
        {
            var item = cb_copyFrom.SelectedItem.ToString();
            short num; var nam = string.Empty;
            if (!Int16.TryParse(item, out num) || num <= 0) nam = item;

            var _newBot = (from lines in DiForm.BotLines
                            where lines.Index == num ||
                            lines.line_lb_name.Text == nam
                            select lines.profile.Bot).FirstOrDefault();
            if (!string.IsNullOrEmpty(_newBot.bnet))
            {
                CurentBot = _newBot;
                Index = num;
                LoadData();
            } else
            {
                var tt = new ToolTip { AutoPopDelay = 5, ForeColor = Color.Red };
                tt.SetToolTip((Button)sender, "Load error");
            }
        }

        private void btn_planMaker_Click(object sender, EventArgs e)
        {
            var helpForm = new Form
                               {
                                   Name = "helpForm",
                                   FormBorderStyle = FormBorderStyle.None,
                                   BackColor = Color.FromArgb(255, 255, 252, 244),
                                   Size = new Size(400, 235),
                                   StartPosition = FormStartPosition.Manual,
                                   Location = new Point(Location.X + Size.Width + 10, Location.Y)
                               };
            helpForm.Controls.Add(new TextBox
                                      {
                                          Name = "tb",
                                          Text = helpText,
                                          WordWrap = true,
                                          Width = helpForm.Width - 20,
                                          Height = helpForm.Height - 32,
                                          Location = new Point(10, 10),
                                          Multiline = true,
                                          Enabled = false,
                                          BackColor = Color.FromArgb(255, 255, 252, 244),
                                          BorderStyle = BorderStyle.None
                                      });
            var btn = new Button
                          {
                              Name = "btn",
                              Text = "Close",
                              TextAlign = ContentAlignment.MiddleCenter,
                              Dock = DockStyle.Bottom,
                              Size = new Size(100, 22),
                              FlatStyle = FlatStyle.Flat
                          };
            btn.Click += delegate(object send, EventArgs ea)
                {
                    var p = (Form)((Button)send).Parent;
                    p.Close();
                    p.Dispose();
                };
            helpForm.Controls.Add(btn);
            Move += delegate { helpForm.Location = new Point(Location.X + Size.Width + 10, Location.Y); };
            helpForm.Show();
            ((Button)sender).Parent.Focus();
        }

        private void schedulePlan_Tooltip(object sender, EventArgs e)
        {
            var tt = new ToolTip();
            Control control;
            switch (((Control)sender).Name)
            {
                case "label12":
                    control = (Label)sender;
                    break;
                case "tb_schedulePlan":
                    control = (TextBox)sender;
                    break;
                default:
                    return;
            }
            tt.AutoPopDelay = int.MaxValue;
            tt.ShowAlways = true;
            tt.SetToolTip(control, helpText);
        }


        private void LoadData()
        {
            tx_key.Text = CurentBot.db_key;
            tx_login.Text = CurentBot.bnet;
            tx_pass.Text = CurentBot.pass;
            tx_routine.Text = CurentBot.db_routine;
            d3_path = CurentBot.d3_path;
            db_path = CurentBot.db_path;

            np_x.Value = (CurentBot.pos.X < (int)np_x.Minimum || CurentBot.pos.X > (int)np_x.Maximum) ? (int)np_x.Minimum : CurentBot.pos.X;
            np_y.Value = (CurentBot.pos.Y < (int)np_y.Minimum || CurentBot.pos.Y > (int)np_y.Maximum) ? (int)np_y.Minimum : CurentBot.pos.Y;
            ns_x.Value = (CurentBot.size.Width < (int)ns_x.Minimum || CurentBot.size.Width > (int)ns_x.Maximum) ? (int)ns_x.Minimum : CurentBot.size.Width;
            ns_y.Value = (CurentBot.size.Height < (int)ns_y.Minimum || CurentBot.size.Height > (int)ns_y.Maximum) ? (int)ns_y.Minimum : CurentBot.size.Height;
        }

        private void Checker(object sender, EventArgs e)
        {
            var count = 0;
            if (d3_path != null && d3_path.Length >= 3)
            {
                count++;
                lb_d3_set.Text = "V";
                lb_d3_set.Font = new Font("Arial", 10, FontStyle.Italic | FontStyle.Bold);
                lb_d3_set.ForeColor = Color.Green;
            }
            else
            {
                lb_d3_set.Text = "X";
                lb_d3_set.Font = new Font("Arial", 10, FontStyle.Bold);
                lb_d3_set.ForeColor = Color.Red;
            }
            if (db_path != null && db_path.Length >= 3)
            {
                count++;
                lb_db_set.Text = "V";
                lb_db_set.Font = new Font("Arial", 10, FontStyle.Italic | FontStyle.Bold);
                lb_db_set.ForeColor = Color.Green;
            }
            else
            {
                lb_db_set.Text = "X";
                lb_db_set.Font = new Font("Arial", 10, FontStyle.Bold);
                lb_db_set.ForeColor = Color.Red;
            }
            if (tx_login.Text != null && tx_login.Text.Length >= 3) count++;
            if (tx_pass.Text != null && tx_pass.Text.Length >= 3) count++;
            if (tx_key.Text != null && tx_key.Text.Length >= 3) count++;
            if (tx_routine.Text != null && tx_routine.Text.Length >= 3) count++;

            try {
                var res = new Regex(@"(^unlim$|^un$|^u$)|([wdri]\d{2,3}(?!\d)(:\d{2})?)").Matches(tb_schedulePlan.Text.ToLower());
                if (res.Count > 0)
                {
                    var resString = string.Empty;
                    bool w, d, r, i;
                    w = d = r = i = false;
                    foreach (var param in res)
                    {
                        switch (param.ToString()[1])
                        {
                            case 'u': resString = "unlim"; break;
                            case 'w': if (!w) { w = true; resString += param + ","; } break;
                            case 'd': if (!d) { d = true; resString += param + ","; } break;
                            case 'r': if (!r) { r = true; resString += param + ","; } break;
                            case 'i': if (!i) { i = true; resString += param + ","; } break;
                        }
                        if (resString == "unlim") break;
                    }
                    tb_schedulePlan.Text = resString;
                    tb_schedulePlan.BackColor = Color.FromArgb(255, 179, 255, 179);
                    count++;
                } else {
                    tb_schedulePlan.BackColor = Color.FromArgb(255, 255, 179, 179);
                }
            } catch {}

            bt_save.Enabled = count >= 7;
        }

        
        const string helpText = "Use \"unlim\", \"un\" or \"u\" for unlimited usage.\r\n" +
                                "Otherwise must be set at least work time range with next format separated with comma:\r\n" +
                                "\"w000:00\" - where W is \"work time\" marker, first pair represent hours [0-999], second pair represent minutes [0-59];\r\n" +
                                "\"d000:00\" - where D is \"delay time\" marker, time format the same as in work time. Default is half of work time;\r\n" +
                                "\"r00\" - where R is \"repeat\" marker, which means how many times plan must be executed before it stop and numbers is simple repeat count [1-99]. If \"work time\" is set, but \"repeat\" is not, then plan will be repeated unlimited times;\r\n" +
                                "\"i000:00\" - where I is \"idle\" marker, time format the same as in work time. This marker uses for setting delay between repeat cycles. If it setted then after last repeat - programm will idle and start over after selected time period.\r\n" +
                                "\r\n" +
                                "All markers not case sensitive.";
    }//*/
}
